import java.io.File;
import java.io.FileOutputStream;


public class AUSMA extends Scheduler implements Runnable {
	int start;
	int stop;
	byte[] BLOCK;
	int[] ITEMID;
	byte[] ITEMVOTE;

	public AUSMA(int start, int stop) {
		this.start = start;
		this.stop = stop;
	}

	void writeBlock() {
		String FILE_NAME = String.format("%s%07d.bin", BLOCK_PATH, start);		File out = new File(FILE_NAME);
		FileOutputStream fos;
		try {
			fos = new FileOutputStream(out);
			fos.write(BLOCK);
		} catch (Exception e) {
			e.printStackTrace();
		}

		System.out.println("Done writing: " + FILE_NAME + " @ "
				+ this.getClass());
	}

	@Override
	public void run() {
		this.ITEMID = new int[USERA.length];
		this.ITEMVOTE = new byte[USERA.length];
		
		int ilen = USERB[0].ilen;
		BLOCK = new byte[(stop - start) * ilen];

		int c = 0;
		for (int bUserID = start; bUserID < stop; bUserID++) {
			for (int i = 0; i < ilen; i++) {
				int bItemID = USERB[bUserID].items[i];

				byte pred = predict(bUserID, bItemID);

				BLOCK[c * ilen + i] = pred;
			}
			c++;
		}

		writeBlock();
	}

	public byte predict(int bUserID, int bItemID) {
		User aUser = USERA[bUserID];
		Item aItem = ITEMA[bItemID];
		int tempUserID;
		double tot = 700;
		int hit = 10;
		
		//Mark all user that voted on bItem with there votes
		for(int i=0; i<aItem.ulen; i++){
			tempUserID = aItem.users[i];
			ITEMID[tempUserID] = bItemID;
			ITEMVOTE[tempUserID] = aItem.votes[i];
		}
		

		for (int historyItemID : aUser.items) {
			Item historyItem = ITEMA[historyItemID];

			for (int linkedUserID : historyItem.users) {
				
				if (ITEMID[linkedUserID] == bItemID) {
					tot += ITEMVOTE[linkedUserID];
					hit++;
				}
			}
		}

		return (byte) (tot / hit);
	}
}
